<template>
  <div class="auth-update">
    <div class="page-header">
      <div class="header-content">
        <h2 class="title">权限管理</h2>
        <p class="description">为用户分配系统功能权限，请谨慎操作</p>
      </div>
      <div class="header-actions">
        <el-button @click="goBack">
          <el-icon><ArrowLeft /></el-icon>
          返回
        </el-button>
        <el-button 
          type="primary" 
          @click="updateAuth"
          :loading="loading"
          :disabled="!hasChanges"
        >
          <el-icon><Check /></el-icon>
          {{ loading ? '保存中...' : '保存修改' }}
        </el-button>
      </div>
    </div>

    <el-card class="auth-card" shadow="never">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <el-icon class="header-icon"><Key /></el-icon>
            <span>权限列表</span>
          </div>
          <div class="header-right">
            <el-button 
              text 
              type="primary" 
              @click="expandAll"
            >
              {{ isExpandAll ? '收起全部' : '展开全部' }}
            </el-button>
            <el-button 
              text 
              type="warning" 
              @click="resetSelection"
              :disabled="!hasChanges"
            >
              重置选择
            </el-button>
          </div>
        </div>
      </template>
      
      <div class="tree-container">
        <el-tree
          ref="authTreeRef"
          :data="authData"
          :props="treeProps"
          node-key="authId"
          :default-checked-keys="checkedKeys"
          :default-expanded-keys="expandedKeys"
          show-checkbox
          check-strictly
          highlight-current
          @check="handleCheck"
        >
          <template #default="{ node, data }">
            <div class="custom-tree-node">
              <span class="node-label">{{ node.label }}</span>
              <el-tag 
                v-if="data.authState === 0" 
                size="small" 
                type="danger"
                effect="light"
              >
                已禁用
              </el-tag>
            </div>
          </template>
        </el-tree>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { get, put, tip } from "@/common";
import { ArrowLeft, Check, Key } from '@element-plus/icons-vue'

const route = useRoute();
const router = useRouter();
const loading = ref(false);
const isExpandAll = ref(false);

// 树形配置
const treeProps = {
  children: 'childAuth',
  label: 'authName',
  disabled: data => data.authState === 0
}

// 权限数据
const authData = ref([]);
const checkedKeys = ref([]);
const originalCheckedKeys = ref([]);
const expandedKeys = ref([]);
const userId = route.query.userId;

// 检查是否有变更
const hasChanges = computed(() => {
  const currentKeys = authTreeRef.value?.getCheckedKeys(false) || [];
  if (currentKeys.length !== originalCheckedKeys.value.length) return true;
  return !currentKeys.every(key => originalCheckedKeys.value.includes(key));
});

// 获取所有权限
const getAllAuth = async () => {
  try {
    const result = await get('/auth/auth-tree');
    authData.value = result.data;
    // 初始展开第一级节点
    expandedKeys.value = authData.value.map(item => item.authId);
  } catch (error) {
    console.error('Failed to fetch auth tree:', error);
    tip.error('获取权限列表失败');
  }
}

// 获取用户已有的权限
const getUserAuthList = async () => {
  try {
    const result = await get(`/user/user-auth?userId=${userId}`);
    checkedKeys.value = result.data;
    originalCheckedKeys.value = [...result.data];
  } catch (error) {
    console.error('Failed to fetch user auth:', error);
    tip.error('获取用户权限失败');
  }
}

// 初始化数据
const initData = async () => {
  await Promise.all([getAllAuth(), getUserAuthList()]);
}
initData();

const authTreeRef = ref();

// 展开/收起所有节点
const expandAll = () => {
  isExpandAll.value = !isExpandAll.value;
  if (isExpandAll.value) {
    authTreeRef.value?.expandAll();
  } else {
    authTreeRef.value?.collapseAll();
    // 保持第一级展开
    expandedKeys.value = authData.value.map(item => item.authId);
  }
};

// 重置选择
const resetSelection = () => {
  checkedKeys.value = [...originalCheckedKeys.value];
  authTreeRef.value?.setCheckedKeys(checkedKeys.value, false);
};

// 处理节点选中
const handleCheck = () => {
  // 可以在这里添加选中时的额外逻辑
};

// 返回上一页
const goBack = () => {
  if (hasChanges.value) {
    ElMessageBox.confirm(
      '有未保存的修改，确定要离开吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
      .then(() => {
        router.go(-1);
      })
      .catch(() => {});
  } else {
    router.go(-1);
  }
};

// 更新权限
const updateAuth = async () => {
  if (!hasChanges.value) {
    tip.warning('未做任何修改');
    return;
  }

  const currentCheckedKeys = authTreeRef.value.getCheckedKeys(false);
  
  loading.value = true;
  try {
    const result = await put("/user/auth-grant", {
      userId: userId,
      authIds: currentCheckedKeys
    });
    tip.success(result.message);
    router.go(-1);
  } catch (error) {
    console.error('Failed to update auth:', error);
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
.auth-update {
  padding: 16px;
}

.page-header {
  margin-bottom: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-content {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.title {
  margin: 0;
  font-size: 20px;
  font-weight: 500;
  color: var(--el-text-color-primary);
}

.description {
  margin: 0;
  font-size: 14px;
  color: var(--el-text-color-secondary);
}

.header-actions {
  display: flex;
  gap: 12px;
}

.auth-card {
  background-color: var(--el-bg-color);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 500;
}

.header-icon {
  font-size: 18px;
  color: var(--el-color-primary);
}

.header-right {
  display: flex;
  gap: 16px;
}

.tree-container {
  min-height: 400px;
  padding: 16px;
  background-color: var(--el-fill-color-blank);
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 4px;
}

:deep(.el-tree) {
  background-color: transparent;
}

:deep(.el-tree-node__content) {
  height: 40px;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.node-label {
  color: var(--el-text-color-primary);
}

:deep(.el-tree-node.is-current > .el-tree-node__content) {
  background-color: var(--el-color-primary-light-9);
}

:deep(.el-card__header) {
  padding: 16px 20px;
  border-bottom: 1px solid var(--el-border-color-lighter);
}

:deep(.el-button) {
  border-radius: 2px;
}
</style>